package com.atguigu.chapter11;

import com.atguigu.chapter5.source.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.junit.Test;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @ClassName: Flink09_Process_Timer
 * @Description:
 * @Author: kele
 * @Date: 2021/4/13 9:58
 *
 * 设置处理时间
 *  1、在流转换的时候添加处理时间
 *          $("xxx").proctime()
 *  2、在创建表(动态表读取数据)的时候添加处理时间
 *          xxxx AS proctime()
 *
 **/
public class Flink09_Process_Timer_Table_SQL {

    /**
     *    在将流转化为表的时候设置处理时间
     */
    @Test
    public void Transfrom(){

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);

        DataStreamSource<WaterSensor> ds = env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60));

        Table table = tenv.fromDataStream(ds, $("id"),
                                            $("ts"),
                                            $("vc"),
                                            $("nowtime").proctime()
                                        );

        table.execute().print();
    }

    /**
     *   用表的方式直接读取数据，在创建表的时候直接指定
     *
     *   在创建表的时候，设置处理时间：
     *          字段名 as proctime()
     */
    @Test
    public void CtreateTbale(){

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);

        tenv.executeSql("create table sen(\n" +
                "  id string,\n" +
                "  ts bigint,\n" +
                "  vc int,\n" +
                //设置处理时间
                "  process_time AS proctime()\n" +
                "  )with(\n" +
                "  'connector' = 'filesystem',\n" +
                "  'path' = 'in/sensor.txt',\n" +
                "  'format' = 'csv'\n" +
                ")");

        tenv.sqlQuery("select * from sen").execute().print();

      //  Table table = tenv.from("sen");

     //   table.execute().print();
    }

}
